<?php

/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2022-04-21
 * Time: 18:17:07
 * Info:
 */

namespace app\admin\middleware;

use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;
use Casbin\WebmanPermission\Permission;
use support\lib\Env;
use think\facade\Db;

/**
 * 访问控制
 */
class AuthCheckAccess implements MiddlewareInterface
{

    /**
     * @param Request  $request
     * @param callable $handler
     *
     * @return String
     */
    public function process(Request $request, callable $handler): Response
    {
        $huicmfConfig = config('huicmf');
        //$token            = $request->header('Hui-Token');
        $session_admin_id = session()->get('session_admin_id');
        $pre_act          = $request->method();

        $controller        = $request->controller;
        $action            = $request->action;
        $currentNode       = $request->path();
        $currentController = str_replace('app\admin\controller\\', "", $controller);
        //验证登录
        //$session_admin_id = session()->get($token);
        if ( ! in_array($currentController, $huicmfConfig['no_login_controller']) && ! in_array($currentNode,
                $huicmfConfig['no_login_node'])) {
            if (empty($session_admin_id)) {
                return error_json('请先登录', '', "/".request()->app.'/login');
            }
            //更新token
            //session()->set($token, $session_admin_id);
        }
        //验证权限
        if ( ! in_array($currentController, $huicmfConfig['no_auth_controller']) && ! in_array($currentNode,
                $huicmfConfig['no_auth_node'])) {
            //获取用户信息
            $adminInfo = cmf_get_admin_info();
            if (empty($adminInfo)) {
                return error_json('登录已过期，请重新登录', '', "/".request()->app.'/login');
            }
            $adminRoleId = ! empty($adminInfo['role_id']) ? $adminInfo['role_id'] : 0;
            if ($adminRoleId != 1) {
                $sub = "admin_role_".$adminRoleId; // 想要访问资源的用户
                $obj = $currentNode; // 将要被访问的资源
                $act = 'GET'; // 用户对资源进行的操作

                //写入权限[案例]
                //Permission::addPolicy($sub, $obj, $act);

                if ( ! Permission::enforce($sub, $obj, $act)) {
                    return error_json('对不起，您没有该资源访问权限');
                }
            }

            // 判断是否为演示环境
            if (Env::get('HUICMF.IS_DEMO', false) && $request->isPost()) {
                return error_json('演示环境下不允许修改');
            }

        }

        return $handler($request);
    }

}
